package com.emm.yixun.aop;

import com.emm.yixun.anotations.MerchantResourcesConfig;
import com.emm.yixun.common.model.ResourcesConfig;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.ResourcesConfigDto;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.system.service.ResourcesConfigServiceFacade;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.constant.EhcacheConstant;
import com.emm.yixun.website.service.CacheUtils;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Created by yangming on 2017/6/15.
 * 注解MerchantResourcesConfig逻辑控制
 */
@Aspect
@Component
public class MerchantResourcesConfigAdvisor {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    public CacheUtils cacheUtils;

    @Autowired
    private ResourcesConfigServiceFacade resourcesConfigServiceFacade;

    @Pointcut("@annotation(com.emm.yixun.anotations.MerchantResourcesConfig)")
    public void controllerAspect(){

    }
    @Before("controllerAspect()")
    public  void doBefore(JoinPoint joinPoint) {
       /*
       1.根据注解配置的资源Code查找定制化对象
       2.如果存在则跳转资源定制化url地址
       3.如果不存在则不做处理，跳转标准版功能
       */
        try {
            //获得注解
            Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
            MerchantResourcesConfig merchantResourcesConfig=method.getAnnotation(MerchantResourcesConfig.class);
            if(null==merchantResourcesConfig){
                return;
            }
            String resourcesCode=merchantResourcesConfig.resourcesCode();
            if(StringUtils.isBlank(resourcesCode)){
                return;
            }
            User user= ShiroUtil.getCurrentUser();
            if(null==user){
                return;
            }
            String cacheKey=user.getMerchantId()+"_"+resourcesCode+"_url";
            Object object=cacheUtils.get(EhcacheConstant.ACTIVE_SESSIONS_CACHE,cacheKey);
            ResourcesConfig resourcesConfig=null;
            if(null==object){
                ResourcesConfigDto resourcesConfigDto=new ResourcesConfigDto();
                resourcesConfigDto.setResourcesCode(resourcesCode);
                resourcesConfigDto.setMerchantId(user.getMerchantId());
                ResponseList<ResourcesConfig> responseList= resourcesConfigServiceFacade.findByDto(resourcesConfigDto);
                if(!responseList.isSuccess() || null==responseList.getEntity() || responseList.getEntity().size()==0){
                    return;
                }
                resourcesConfig=responseList.getEntity().get(0);
                cacheUtils.put(EhcacheConstant.ACTIVE_SESSIONS_CACHE,cacheKey,resourcesConfig);
            }else{
                resourcesConfig=(ResourcesConfig)object;
            }

            String url=resourcesConfig.getUrl();
            if(StringUtils.isBlank(url)){
                return;
            }
            HttpServletResponse response=null;
            HttpServletRequest request=null;
            Object[] args = joinPoint.getArgs();
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof HttpServletRequest) {
                    request = (HttpServletRequest) args[i];
                }
                if (args[i] instanceof HttpServletResponse) {
                    response = (HttpServletResponse) args[i];
                }
            }
            if(null==request || null==response){
                return;
            }
            request.getRequestDispatcher(url).forward(request,response);
        }catch (Exception e){
            logger.error("商户定制需求跳转失败："+e);
        }

    }
}
